<template>
  <div>
    <el-form :model="unifyData" label-position="right">
      <!--按业务配置-->
      <el-card shadow="never" v-if="configType === '2'" style="margin-bottom: 20px">
        <div class="header-card">
          <div style="display: flex">
            <el-form-item label="业务类型" label-width="80px">
              <el-select v-model="unifyData.businessConfigType" @change="handleBusinessConfigType"
                         placeholder="请选业务类型">
                <el-option label="渠道业务" value="1"></el-option>
                <el-option label="自营业务" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="50px">
              <el-switch :value="unifyData.configStatus" @input="handleSwitch" active-value="1" inactive-value="2"
                         :active-color="activeColor" :inactive-color="inactiveColor" :active-text="activeText"
                         :inactive-text="inactiveText" class="switchStyle"/>
            </el-form-item>
          </div>
          <div style="min-width: 0">
            <template v-if="dispositionBoole === 1">
              <el-button type="primary" @click="handleBoole">配置签署流程</el-button>
            </template>
            <template v-if="dispositionBoole === 2">
              <el-button size="medium" @click="handleCancelSave">取消</el-button>
              <el-button type="primary" size="medium" @click="handleSubmint">保存</el-button>
            </template>
          </div>
        </div>
      </el-card>

      <!-- 统一配置 -->
      <el-card class="box-card" shadow="never">
        <div slot="header" class="header-card" v-if="configType === '1'">
          <div>
            <el-form-item label-width="10px">
              <el-switch :value="unifyData.configStatus" @input="handleSwitch" active-value="1" inactive-value="2"
                         :active-text="activeText" :inactive-text="inactiveText" class="switchStyle"
                         :active-color="activeColor"
                         :inactive-color="inactiveColor">
              </el-switch>
            </el-form-item>
          </div>
          <div style="min-width: 0">
            <template v-if="dispositionBoole === 1">
              <el-button type="primary" @click="handleBoole">配置签署流程</el-button>
            </template>
            <template v-if="dispositionBoole === 2">
              <el-button size="medium" @click="handleCancelSave">取消</el-button>
              <el-button type="primary" size="medium" @click="handleSubmint">保存</el-button>
            </template>
          </div>
        </div>

        <div class="box-container">
          <div class="box-div" v-for="(item, index) in unifyData.saveList" :key="index + 'ss'">
            <!-- 左边三图标-->
            <!--<el-button v-if="dispositionBoole === 2" type="text" style=" font-size: 20px;" icon="el-icon-s-fold"/>-->

            <!--中间表格-->
            <div class="box-middle">
              <!--经办人签字     法定代表人签字     -->
              <div style="font-size: 14px" v-if="['1', '2'].includes(item.taskType)">
                {{ hadnleTaskName(item.taskType) }}
              </div>

              <!--个人审批   企业签章-->
              <template v-else>
                <div style="display: flex;justify-content: space-between;margin-bottom: 15px;">
                  <div style="font-size: 14px">
                    {{ hadnleTaskName(item.taskType) }}
                  </div>
                  <div style="font-size: 14px">
                    <span style="padding-right: 15px">未配置允许跳过此节点</span>
                    <el-switch v-model="item.nodeType" active-value="2" inactive-value="0" active-text="开"
                               inactive-text="关" :disabled="dispositionBoole === 1" :active-color="activeColor"
                               :inactive-color="inactiveColor" class="switchStyle"/>
                  </div>
                </div>
                <div style="width: 100%">
                  <el-table :data="item.saveList" border size="mini">
                    <el-table-column align="center" type="index" width="38"/>
                    <el-table-column align="center" v-if="item.taskType === '3'" label="审批人" width="80"
                                     show-overflow-tooltip prop="approvalName"/>
                    <el-table-column align="center" v-if="item.taskType === '4'" label="签章人" width="80"
                                     show-overflow-tooltip prop="approvalName"/>
                    <el-table-column align="center" label="联系方式" width="100" prop="approvalPhone"/>
                    <el-table-column align="center" label="关联出租方" prop="deptGroupIdList">
                      <template #default="{ row }">
                        <span>
                          {{row.deptGroupNameList| handleDeptGroupNameList}}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="90" v-if="dispositionBoole === 2">
                      <template #default="{ row, $index }">
                        <el-button size="mini" type="text" @click="handleEdit(index,$index,row,item.taskType)">
                          编辑
                        </el-button>
                        <el-button size="mini" type="text" @click=" handleDele(index,$index)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>

                    <template v-slot:append v-if="dispositionBoole === 2">
                      <div class="flex-xy-center" style="height: 30px">
                        <e-button type="text" icon="eel-icon-plus" @click="handleAdd(item.taskType,index)">
                          <span v-if="item.taskType ==='3'">新增审批人</span>
                          <span v-if="item.taskType ==='4'">新增签章人</span>
                        </e-button>
                      </div>
                    </template>
                  </el-table>
                </div>
              </template>
            </div>

            <!--右边删除图标-->
            <el-button v-if="dispositionBoole === 2" type="text" style="font-size: 20px" icon="el-icon-delete"
                       @click="handleDeleUnif(index)"/>
          </div>

          <!-- 底部添加节点-->
          <div class="box-div" style="display: flex; justify-content: center" v-if="dispositionBoole === 2">
            <el-button type="text" style="font-size: 14px; margin-right: 20px" @click="handleAddNode"
                       v-if="nodeValue !== ''" icon="el-icon-plus">
              添加节点
            </el-button>
            <el-select v-model="nodeValue" placeholder="请选择节点">
              <el-option v-for="item in nodeList" :key="item.value" :label="item.label" :disabled="item.disabled"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </el-card>
    </el-form>

    <!--弹框-->
    <el-dialog :title="title" :visible.sync="dialogVisible" append-to-body width="30%">
      <el-form :model="dialogFrom" ref="dialogFrom" :rules="rules" label-position="right">
        <el-form-item :label="labelName" label-width="95px" prop="approvalName"
                      :rules="{required: true, message: '请搜索',trigger: 'change',}">
          <el-autocomplete v-model.trim="dialogFrom.approvalName" :fetch-suggestions="requireQuerySearchAsync"
                           style="width: 100%" :placeholder="`请搜索${labelName}`" :trigger-on-focus="false"
                           @select="handleSelect">
            <template slot-scope="{ item }">
              <div class="product-item">
                <div class="name">
                  <span>{{ item.nickName }}</span>
                </div>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="选择出租方" label-width="95px" prop="deptGroupIdList">
          <el-select v-model="dialogFrom.deptGroupIdList" multiple placeholder="请选择出租方" @change="handleChange"
                     style="width: 100%">
            <el-option v-for="item in rentOutList" :label="item.deptName" :value="item.deptId.toString()"
                       :key="item.deptId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubRentOut">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  rentOutexclude,
  submintAddList,
  getList,
} from "@/api/contractTemplate/electronicContract.js";

export default {
  name: "unify", //统一配置
  props: {
    configType: {
      type: String,
      default: "",
    },
  },
  computed: {
    hadnleTaskName() {
      return function (val) {
        let a = this.nodeList
            .map((a) => {
              if (a.value === val) {
                return a.label;
              }
            })
            .filter((a) => a)[0];
        return a;
      };
    },
  },
  watch: {
    "unifyData.saveList": {
      handler: function (newValue, oldValue) {
        if (newValue) {
          let index1 = newValue.findIndex((i) => i.taskType === "1");
          let index2 = newValue.findIndex((i) => i.taskType === "2");
          let index3 = newValue.findIndex((i) => i.taskType === "4");
          if (index1 !== -1) {
            this.nodeList[0].disabled = true;
          } else {
            this.nodeList[0].disabled = false;
          }
          if (index2 !== -1) {
            this.nodeList[1].disabled = true;
          } else {
            this.nodeList[1].disabled = false;
          }
          if (index3 !== -1) {
            this.nodeList[3].disabled = true;
          } else {
            this.nodeList[3].disabled = false;
          }
        }
      },
      immediate: true,
      deep: true,
    },
    configType: {
      handler(newValue) {
        if (newValue) {
          this.handleGetList();
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    var validatorDeptId = (rule, value, callback) => {
      console.log(value, "-=-=-=");
      if (value && value.length && value.length === 0) {
        callback(new Error("请选择出租方"));
      } else {
        let ids = value[value.length - 1];
        let arr = this.unifyData.saveList[this.listIndex].saveList || [];
        if (arr && arr.length === 0) {
          callback();
        } else {
          let listData = [];
          for (let i = 0; i < arr.length; i++) {
            //新增
            if (this.boole) {
              let list = arr[i].deptGroupIdList ? arr[i].deptGroupIdList : [];
              listData = listData.concat(list);
            } else {
              //编辑
              if (i !== this.tableDataIndex) {
                let list1 = arr[i].deptGroupIdList
                    ? arr[i].deptGroupIdList
                    : [];
                listData = listData.concat(list1);
              }
            }
          }
          if (listData.indexOf(ids) !== -1) {
            callback(new Error("出租方已存在"));
          } else {
            callback();
          }
        }
      }
    };
    return {
      value: "",
      rentOutList: [],
      dialogFrom: {
        deptGroupIdList: [],
        deptGroupNameList: [],
        deptGroupIds: "",
        deptGroupName: "",
        approvalName: "",
        approvalId: "",
        approvalPhone: "",
      },
      nodeList: [
        {label: "经办人签字", value: "1", disabled: false},
        {label: "法定代表人签字", value: "2", disabled: false},
        {label: "个人审批", value: "3", disabled: false},
        {label: "企业签章", value: "4", disabled: false},
      ],
      nodeValue: "",
      unifyData: {
        configType: this.configType,
        configStatus: "2",
        businessConfigType: "1",
        saveList: [],
      },
      title: "",
      dialogVisible: false,
      indexNode: 0,
      disabled: false,
      labelName: "",
      listIndex: 0, //列表下标
      tableDataIndex: 0, //表格下标
      boole: false,
      dispositionBoole: 1,
      activeColor: "#1890FF",
      inactiveColor: "#CDCDCD",
      activeText: "启用",
      inactiveText: "禁用",
      rules: {
        deptGroupIdList: [
          {
            required: true,
            validator: validatorDeptId,
            trigger: "change",
          },
        ],
      },
      // validator: validatorDeptId,
    };
  },
  created() {
    this.handleRentOut();
    //this.handleGetList();
  },
  mounted() {
  },

  filters: {
    handleDeptGroupNameList(val) {
      let str = "";
      if (val && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          str += val[i];
          if (i !== val.length - 1) {
            str = str + "、";
          }
        }
      } else {
        str = "";
      }
      return str;
    },
  },
  methods: {
    handleBoole() {
      this.dispositionBoole = 2;
    },

    handleBusinessConfigType(val) {
      this.unifyData.businessConfigType = val;
      this.handleGetList();
    },

    //获取列表
    async handleGetList() {
      let obj = {
        configType: this.configType,
        businessConfigType: this.unifyData.businessConfigType,
      };
      try {
        const res = await getList(obj);
        if (res.data) {
          this.unifyData = res.data;
        } else {
          this.unifyData.saveList = [];
        }
      } catch (e) {
        console.error("获取失败", e);
      }
    },

    //switch事件
    handleSwitch() {
      if (this.unifyData.saveList.length === 0) {
        this.$message({
          type: "warning",
          message: "尚未配置签署流程",
        });
        return;
      }
      let msg = "";
      if (this.unifyData.configStatus === "2") {
        msg = "开启";
      }
      if (this.unifyData.configStatus === "1") {
        msg = "禁用";
      }
      this.$confirm(`确认${msg}此签署流程?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            if (msg === "开启") {
              this.unifyData.configStatus = "1";
            }
            if (msg === "禁用") {
              this.unifyData.configStatus = "2";
            }
            this.handleSaveList("switch", msg);
          })
          .catch(() => {
            if (msg === "开启") {
              this.unifyData.configStatus = "2";
            }
            if (msg === "禁用") {
              this.unifyData.configStatus = "1";
            }
          });
    },

    //添加节点
    handleAddNode() {
      let obj = {
        nodeType: "",
        taskType: this.nodeValue,
        configSort: 0,
        saveList: [],
      };
      if (["1", "2", "4"].includes(this.nodeValue)) {
        let index = this.unifyData.saveList.findIndex(
            (a) => a.taskType === this.nodeValue
        );
        if (index === -1) {
          this.indexNode++;
          obj.configSort = this.indexNode;
          this.unifyData.saveList.push(obj);
        }
      }

      if (["3"].includes(this.nodeValue)) {
        this.indexNode++;
        obj.configSort = this.indexNode;
        this.unifyData.saveList.push(obj);
      }
      this.nodeValue = "";
    },

    //删除节点
    handleDeleUnif(index) {
      this.$confirm("确认删除签署节点?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.unifyData.saveList.splice(index, 1);
            this.$message({type: "success", message: "删除成功!"});
          })
          .catch(() => {
            this.$message({type: "info", message: "已取消删除"});
          });
    },

    //获取出租方
    handleRentOut() {
      rentOutexclude({deptType: 2}).then((res) => {
        if (res.code === 200) {
          this.rentOutList = res.data;
          this.rentOutList.forEach((item) => {
            item.deptId.toString();
          });
        }
      });
    },

    //获取审批人
    async requireQuerySearchAsync(queryString, cb) {
      let results;
      const res = await getUserList({nickName: queryString});
      if (res.code === 200) {
        results = res.data;
      } else {
        results = [];
      }

      cb(results);
      if (results.length === 0) {
        this.dialogFrom.approvalId = '';
        this.dialogFrom.approvalName = '';
        this.dialogFrom.approvalPhone = '';
      }
    },

    handleSelect(val) {
      if (val) {
        this.dialogFrom.approvalId = val.userId;
        this.dialogFrom.approvalName = val.nickName;
        this.dialogFrom.approvalPhone = val.phonenumber;
      }
    },

    handleChange(val) {
      let list;
      if (val.length && val.length > 0) {
        list = this.rentOutList
            .map((a) => {
              if (val.includes(a.deptId.toString())) {
                return a.deptName;
              }
            })
            .filter((a) => a !== undefined);
      }
      this.$set(this.dialogFrom, "deptGroupNameList", list);
      this.dialogFrom.deptGroupIdList = val;
    },

    //编辑表格
    handleEdit(index, index_, row, type) {
      this.listIndex = index;
      this.tableDataIndex = index_;
      this.dialogFrom = row;

      if (type === "3") {
        this.title = "编辑审批人";
        this.labelName = "审批人";
      }

      if (type === "4") {
        this.title = "编辑签章人";
        this.labelName = "签章人";
      }
      this.dialogVisible = true;
      this.boole = false;
    },

    //删除表格
    handleDele(index, index_) {
      this.$confirm("确认删除数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.unifyData.saveList[index].saveList.splice(index_, 1);
            this.$message({type: "success", message: "删除成功!"});
          })
          .catch(() => {
            this.$message({type: "info", message: "已取消删除"});
          });
    },

    handleAdd(type, index) {
      if (type === "3") {
        this.title = "新增审批人";
        this.labelName = "审批人";
      }

      if (type === "4") {
        this.title = "新增签章人";
        this.labelName = "签章人";
      }
      this.dialogVisible = true;
      this.listIndex = index;
      this.boole = true;
      this.tableDataIndex = -1;
    },

    //quxiao
    handleCancel() {
      this.dialogFrom = {
        deptGroupNameList: [],
        deptGroupIdList: [],
        approvalName: "",
        approvalId: "",
        approvalPhone: "",
      };
      this.dialogVisible = false;
    },

    //弹框
    handleSubRentOut() {
      this.$refs.dialogFrom.validate((valid) => {
        if (valid) {
          console.log(this.boole, this.listIndex, this.unifyData.saveList);
          if (this.boole) {
            if (this.unifyData.saveList[this.listIndex].saveList === null) {
              this.unifyData.saveList[this.listIndex].saveList = [];
            }
            this.unifyData.saveList[this.listIndex].saveList.push(
                this.dialogFrom
            );
          }
          this.handleCancel();
        }
      });
    },

    //取消保存
    handleCancelSave() {
      this.$confirm("此操作取消不保存配置内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.$tab.refreshPage();
            this.$message({
              type: "success",
              message: "取消成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
    },

    //提交按钮
    handleSubmint() {
      if (this.unifyData.saveList.length === 0) {
        this.$message({
          type: "warning",
          message: "请至少添加一条节点",
        });
        return;
      }
      this.$confirm("确认保存配置内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.handleSaveList("button");
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
    },

    //提交数据
    handleSaveList(type, val) {
      submintAddList(this.unifyData).then((res) => {
        let message = "";
        if (type === "button") {
          this.dispositionBoole = 1;
          message = "保存成功";
        }
        if (type === "switch") {
          message = `${val}成功`;
        }
        this.$message({
          type: "success",
          message: message,
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 20px;
}

.header-card {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.box-container {
  width: 800px;
  margin: 0 auto;

  .box-div {
    width: 80%;
    display: flex;
    margin: 0 auto;
    margin-bottom: 20px;
    gap: 0 15px;
    align-items: start;

    .box-middle {
      flex: 1;
      min-width: 0;
      padding: 20px 20px;
      box-sizing: border-box;
      border: 1px solid rgba(215, 215, 215, 1);
      background-color: rgba(255, 255, 255, 1);
      border-radius: 4px;
    }
  }
}

.switchStyle .el-switch__label {
  position: absolute;
  display: none;
  color: #ffffff;
  font-size: 14px;
}

.el-switch__core {
  background-color: rgba(166, 166, 166, 1);
}

.switchStyle .el-switch__label--left {
  z-index: 9;
  left: 22px;
}

.switchStyle .el-switch__label--right {
  z-index: 9;
  left: -2px;
}

.switchStyle .el-switch__label.is-active {
  display: block;
}

.switchStyle.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 60px !important;
}
</style>
